package demo.android.myapplication.demos.touch

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.MotionEvent.*
import android.view.View
import cn.android.basic.decodeBitmap
import cn.android.basic.dp
import cn.android.basic.int
import demo.android.myapplication.R

/**
 * Created by guoshiwen on 2021/7/27.
 */
class MultiPointView1 @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val source = decodeBitmap(R.mipmap.ic_launcher_copy, 200.dp.int)
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var offsetX = 0f
    private var offsetY = 0f
    private val down = PointF()
    private var trackingId = 0

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawBitmap(source, offsetX, offsetY, paint)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when(event.actionMasked) {
            ACTION_DOWN, ACTION_POINTER_DOWN -> {
                down.set(event.getX(event.actionIndex), event.getY(event.actionIndex))
                trackingId = event.getPointerId(event.actionIndex)
            }
            ACTION_MOVE -> {
                val index = event.findPointerIndex(trackingId)
                if(index < 0) return true
                offsetX += event.getX(index) - down.x
                offsetY += event.getY(index) - down.y

                down.set(event.getX(index), event.getY(index))
                invalidate()
            }
            ACTION_UP -> {

            }
        }
        return true
    }
}